"""
小白职业学校的内部APP
"""
import asyncio
import datetime
import hashlib

import httpx
# import base64
# from Crypto.Cipher import AES

import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW, CENTER, RIGHT
from toga.validators import MatchRegex
# from toga.dialogs import ErrorDialog, InfoDialog, OpenFileDialog

class autowork(toga.App):
    SERVER_URL = 'http://192.168.0.240:7729/api/v2'
    logo = None
    logout = False
    current_user_data = {
        'username': '',
        'usertoken': '',
        'uploads': [],
    }

    async def upload_audio_file(self, button):
        file_path = ''
        from toga.platform import current_platform
        if current_platform == "android":
            from android.content import Intent,ContentResolver
            from android.provider import MediaStore

            context = self._impl.native

            fileChose = Intent(Intent.ACTION_GET_CONTENT)
            fileChose.addCategory(Intent.CATEGORY_OPENABLE)
            fileChose.setType("audio/*")

            results = await self._impl.intent_result(Intent.createChooser(fileChose, "请选择音频文件"))
            data = results['resultData'].getData()
            phoneRoot = '/storage/emulated/0/'
            dataList=str(data).split(phoneRoot)
            if len(dataList)>1:
                file_path = phoneRoot + dataList[1]
            else:
                def getFilePathByURI(uri):
                    if uri == None: return None
                    scheme = uri.getScheme()
                    filePath = None
                    if scheme == None:
                        filePath = uri.getPath()
                    elif ContentResolver.SCHEME_FILE == scheme:
                        filePath = uri.getPath()
                    elif ContentResolver.SCHEME_CONTENT == scheme:
                        cursor = context.getContentResolver().query(uri, None, None, None, None)
                        if cursor != None:
                            if cursor.moveToFirst():
                                columnName = MediaStore.Images.Media.DATA
                                if uri == MediaStore.Images.Media.EXTERNAL_CONTENT_URI:
                                    columnName = MediaStore.Images.Media.DATA
                                elif uri == MediaStore.Audio.Media.EXTERNAL_CONTENT_URI:
                                    columnName = MediaStore.Audio.Media.DATA
                                elif uri == MediaStore.Video.Media.EXTERNAL_CONTENT_URI:
                                    columnName = MediaStore.Video.Media.DATA
                                imageColumnIndex = cursor.getColumnIndex(columnName)
                                if imageColumnIndex < 0:
                                    # filePath = phoneRoot+cursor.getString(0).split(":", 1)
                                    result = cursor.getString(0).split(":", 1)
                                    if len(result) > 1:
                                        filePath = phoneRoot + result[1]
                                    # else:
                                        # 这里可以添加处理长度不足的情况，例如抛出异常或使用默认值
                                        # await self.main_window.error_dialog("错误", message="文件选择失败")
                                        # filePath = phoneRoot  # 或者 raise Exception("Invalid string format")
                                else:
                                    filePath = cursor.getString(imageColumnIndex)
                            cursor.close()
                    return filePath
                file_path = getFilePathByURI(data)
        else:
            # 打开文件对话框，选择文件
            # file_path = await self.main_window.dialog(OpenFileDialog(
            #     title='请选择音频文件',
            #     file_types=['mp3', 'wav', 'wma', 'amr', 'm4a', 'ogg'],
            #     multiple_select=True
            # ))
            file_path = await self.main_window.open_file_dialog(title='请选择音频文件',
                                                                file_types=['mp3', 'wav', 'wma', 'amr', 'm4a', 'ogg'],
                                                                multiple_select=True)
            file_path = list(map(lambda x: str(x), file_path))
        if file_path:
            try:
                res = await httpx.AsyncClient().request("POST",
                              url=self.SERVER_URL + "/upload",
                              files={"file": open(file_path[0], 'rb')},
                              headers={'Content-Type': 'multipart/form-data'}
                            )
                if res.json()['code'] == 200:
                    # AES解密data(key=xiaobaixueyuan@@)
                    # key = b'xiaobaixueyuan@@'
                    # cipher = AES.new(key, AES.MODE_ECB)
                    # data = base64.b64decode(res.json()['data'])
                    # data = cipher.decrypt(data)

                    self.current_user_data['uploads'].append(res.json()['data'])
                    await self.main_window.info_dialog("上传成功", message="上传成功，可以继续选择需要上传的音频文件")
                else:
                    await self.main_window.error_dialog("上传失败", message="上传失败，请重新尝试！")
                    # await self.main_window.dialog(ErrorDialog("上传失败", message="上传失败，请重新尝试！"))
            except httpx.ConnectTimeout as e:
                await self.main_window.error_dialog("上传失败", message="网络请求超时！")
            except Exception as e:
                await self.main_window.error_dialog("上传失败", message=f"上传失败:{e}请重新尝试！")

    def startup(self):
        """  登录页  """
        if not self.logout:
            self.main_box = toga.Box(style=Pack(direction=COLUMN, background_color='#7ed6c6'))
        self.logout = False

        self.logo_box = toga.Box(style=Pack(direction=ROW, background_color='#7ed6c6', alignment=CENTER))

        self.username_input = toga.TextInput(placeholder='请输入用户名...', style=Pack(padding=5, flex=1))
        self.password_input = toga.PasswordInput(placeholder='请输入密码...', style=Pack(padding=5, flex=1))

        self.checkbutton = toga.Button('登录', on_press=self.login, style=Pack(padding=5, flex=1))
        if not self.logo:
            self.logo = toga.ImageView(id='images', image='./resources/logo.png')
            self.logo.style.update(alignment=CENTER,
                                   padding_top=20,
                                   padding_bottom=100,
                                   flex=1,
                                   background_color='#7ed6c6')
        self.main_box.clear()
        self.main_box.add(self.logo)
        self.main_box.add(self.username_input)
        self.main_box.add(self.password_input)
        self.main_box.add(self.checkbutton)

        self.main_window = toga.MainWindow(title='登录页')
        self.main_window.content = self.main_box
        self.main_window.show()

    async def login(self, button):
        if self.username_input.value == '' or self.password_input.value == '':
            # self.main_window.dialog(ErrorDialog("错误:", "用户名或密码不能为空，请重新尝试！"))
            await self.main_window.error_dialog("错误:", "用户名或密码不能为空，请重新尝试！")
            return
        else:
            try:
                # password进行md5加密，盐值：xiaobai
                md5 = hashlib.md5()
                md5.update((self.password_input.value + 'xiaobai').encode(encoding='utf-8'))
                self.password_input.value = md5.hexdigest()
                res = await httpx.AsyncClient().request("POST",
                                      url=self.SERVER_URL + "/login",
                                      json={
                                          "username": self.username_input.value,
                                          "password": self.password_input.value
                                      },
                                      headers={'Content-Type': 'application/json'}
                                    )
                if res.json()['code'] == 200:
                    self.current_user_data['username'] = self.username_input.value
                    self.current_user_data['usertoken'] = res.json()['data']['token']
                    self.indexPage()
                else:
                    await self.main_window.error_dialog("错误:", res.json()['message'])
            except httpx.ConnectTimeout as e:
                await self.main_window.error_dialog("错误:", "网络请求超时！")
            except Exception as e:
                await self.main_window.error_dialog("错误:", str(e))

    def goLoginPage(self, button):
        self.current_user_data['username'] = ''
        self.current_user_data['usertoken'] = ''
        self.logout = True
        self.startup()

    def goIndexPage(self, button):
        if self.current_user_data['username'] != '' and self.current_user_data['usertoken'] != '':
            self.indexPage()
        else:
            self.startup()

    def goMyPage(self, button):
        if self.current_user_data['username'] != '' and self.current_user_data['usertoken'] != '':
            self.myPage()
        else:
            self.startup()

    def goDailyPage(self, button):
        if self.current_user_data['username'] != '' and self.current_user_data['usertoken'] != '':
            self.dailyPage()
        else:
            self.startup()

    def myPage(self):
        # self.main_box = toga.Box(style=Pack(direction=COLUMN, background_color='#7ed6c6'))
        self.navigation = toga.Box(style=Pack(direction=ROW, background_color='#7ed6c6'),
                                   children=[
            toga.Button('首页', on_press=self.goIndexPage),
            toga.Button('我的', on_press=self.goMyPage),
            toga.Button('日报', on_press=self.goDailyPage),
            toga.Button('退出', on_press=self.goLoginPage),
        ])

        # 展示 用户信息
        self.user_info = toga.Box(style=Pack(direction=COLUMN, background_color='#7ed6c6'),
                                  children=[
            toga.Label(text="用户名：" + self.current_user_data['username'], style=Pack(padding=5, flex=1)),
            toga.Label(text="用户Token：" + self.current_user_data['usertoken'], style=Pack(padding=5, flex=1)),
        ])
        self.main_box.clear()
        self.main_box.add(self.logo)
        self.main_box.add(self.navigation)

        self.main_box.add(self.user_info)
        self.main_window = toga.MainWindow(title="我的")
        self.main_window.content = self.main_box
        self.main_window.show()

    async def submit_daily_info(self, button):
        if not self.user_name_input.value or not self.user_phone_input.value:

            # await self.main_window.dialog(ErrorDialog("提交失败", message="请填写完整的日报信息"))
            await self.main_window.error_dialog("提交失败", message="请填写完整的日报信息")
            return
        elif self.user_phone_input.is_valid == False:
            # await self.main_window.dialog(ErrorDialog("提交失败", message="号码非法，请输入11位合法手机号码！"))
            await self.main_window.error_dialog("提交失败", message="号码非法，请输入11位合法手机号码！")
            return
        else:
            submit_data = {
                'username': self.user_name_input.value,
                'phone': self.user_phone_input.value,
                'date': datetime.datetime.strftime(self.user_date_input.value, "%Y-%m-%d"),
                'company': self.user_company_input.value,
                'record': self.current_user_data["uploads"],
            }
            try:
                res = await httpx.AsyncClient().request("POST",
                                        url=self.SERVER_URL + "/daily",
                                        json=submit_data,
                                        headers={'content-type': 'application/json'},
                                    )
                # 提交信息
                if res.json()['code'] == 200:
                    # msg = await res.json()['message']
                    # data = await res.json()['data']
                    # await self.main_window.dialog(InfoDialog("提交成功", message="提交成功"))
                    await self.main_window.info_dialog("提交成功", message="提交成功")
                else:
                    # await self.main_window.dialog(ErrorDialog("提交失败", message="提交失败"))
                    await self.main_window.error_dialog("提交失败", message="提交失败")
            except httpx.ConnectTimeout as e:
                # await self.main_window.dialog(ErrorDialog("提交失败", message="网络请求超时！"))
                await self.main_window.error_dialog("提交失败", message="网络请求超时！")
            except Exception as e:
                # await self.main_window.dialog(ErrorDialog("提交失败", message=str(e)))
                await self.main_window.error_dialog("提交失败", message=str(e))

    def   dailyPage(self):
        # self.main_box = toga.Box(style=Pack(direction=COLUMN, background_color='#7ed6c6'))
        self.navigation = toga.Box(style=Pack(direction=ROW, background_color='#7ed6c6'), children=[
            toga.Button('首页', on_press=self.goIndexPage),
            toga.Button('我的', on_press=self.goMyPage),
            toga.Button('日报', on_press=self.goDailyPage),
            toga.Button('退出', on_press=self.goLoginPage),
        ])
        self.main_box.clear()
        self.main_box.add(self.logo)
        self.main_box.add(self.navigation)
        self.user_name_input = toga.TextInput(value=self.current_user_data['username'],
                                              style=Pack(padding=5, flex=1))
        self.user_name_info = toga.Box(style=Pack(direction=ROW,
                                                  background_color='#7ed6c6',
                                                  padding=5,
                                                  padding_left=20,
                                                  padding_right=20),
                                       children=[
            toga.Label(text="*", style=Pack(padding_top=5, padding_bottom=5, padding_left=5, color='red')),
            toga.Label(text="用户名称：", style=Pack(padding_top=5, padding_bottom=5, padding_right=5, text_align=RIGHT)),
            self.user_name_input,
        ])

        self.user_phone_input = toga.TextInput(placeholder='请输入手机号',
                                               validators=[MatchRegex(r'^1[3456789]\d{9}$',
                                                                      error_message='请输入11位合法手机号码',
                                                                      allow_empty=False)],
                                               style=Pack(padding=5, flex=1))
        self.user_phone_info = toga.Box(style=Pack(direction=ROW,
                                                   background_color='#7ed6c6',
                                                   padding=5,
                                                   padding_left=20,
                                                   padding_right=20),
                                        children=[
            toga.Label(text="*", style=Pack(padding_top=5, padding_bottom=5, padding_left=5, color='red')),
            toga.Label(text="手机号码：", style=Pack(padding_top=5, padding_bottom=5, padding_right=5, text_align=RIGHT)),
            self.user_phone_input,
        ])

        self.user_date_input = toga.DateInput(max=datetime.datetime.now(),
                                              min=datetime.datetime.now() - datetime.timedelta(days=30),
                                              style=Pack(padding=5, flex=1))
        self.user_date_info = toga.Box(style=Pack(direction=ROW,
                                                  background_color='#7ed6c6',
                                                  padding=5,
                                                  padding_left=20,
                                                  padding_right=20),
                                       children=[
            toga.Label(text=" ", style=Pack(padding_top=5, padding_bottom=5, padding_left=5)),
            toga.Label(text="面试日期：", style=Pack(padding_top=5, padding_bottom=5, padding_right=5, text_align=RIGHT)),
            self.user_date_input,
        ])

        self.user_company_input = toga.TextInput(placeholder='请输入面试公司名称', style=Pack(padding=5, flex=1))
        self.user_company_info = toga.Box(style=Pack(direction=ROW,
                                                     background_color='#7ed6c6',
                                                     padding=5,
                                                     padding_left=20,
                                                     padding_right=20),
                                          children=[
            toga.Label(text=" ", style=Pack(padding_top=5, padding_bottom=5, padding_left=5)),
            toga.Label(text="面试公司：", style=Pack(padding_top=5, padding_bottom=5, padding_right=5, text_align=RIGHT)),
            self.user_company_input,
        ])

        self.user_audio_info = toga.Box(style=Pack(direction=ROW,
                                                 background_color='#7ed6c6',
                                                 padding=5,
                                                 padding_left=20,
                                                 padding_right=20),
                                      children=[
            toga.Label(text=" ", style=Pack(padding_top=5, padding_bottom=5, padding_left=5)),
            toga.Label(text="音频地址：", style=Pack(padding_top=5, padding_bottom=5, padding_right=5, text_align=RIGHT)),
            toga.Button(text="录音上传", on_press=self.upload_audio_file, style=Pack(padding=5, flex=1)),
        ])

        self.daily_info = toga.Box(style=Pack(direction=COLUMN,
                                              background_color='#7ed6c6',
                                              padding=5,
                                              padding_left=20,
                                              padding_right=20),
                                   children=[
            self.user_name_info,
            self.user_phone_info,
            self.user_date_info,
            self.user_company_info,
            self.user_audio_info,
            toga.Button(text="提 交", on_press=self.submit_daily_info, style=Pack(padding=5,
                                                                                  padding_left=20,
                                                                                  padding_right=20,
                                                                                  flex=1))
        ])

        self.main_box.add(self.daily_info)

        self.main_window = toga.MainWindow(title="日报")
        self.main_window.content = self.main_box
        self.main_window.show()

    def indexPage(self):
        # self.main_box = toga.Box(style=Pack(direction=COLUMN,
        #                                     background_color='#7ed6c6',
        #                                     padding_top=0,
        #                                     padding_bottom=0))
        self.navigation = toga.Box(style=Pack(direction=ROW, background_color='#7ed6c6', padding_bottom=0), children=[
            toga.Button('首页', on_press=self.goIndexPage),
            toga.Button('我的', on_press=self.goMyPage),
            toga.Button('日报', on_press=self.goDailyPage),
            toga.Button('退出', on_press=self.goLoginPage),
        ])
        self.main_box.clear()
        self.main_box.add(self.logo)
        self.main_box.add(self.navigation)
        self.main_window = toga.MainWindow(title="首页")
        self.main_window.content = self.main_box
        self.main_window.show()

def main():
    return autowork()
